package com.auxgroup.hr.front.site.co.personnel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.person.DailyRespVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.utils.WebServiceClient;
import com.auxgroup.hr.front.commons.utils.WebServiceUtils;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.PsCEmpMatchVw;
import com.auxgroup.hr.front.dao.domain.PsCEmplCrdVw;
import com.auxgroup.hr.front.dao.domain.PsCLaveDtlVw;
import com.auxgroup.hr.front.service.personnal.DailyCalendarService;
import com.auxgroup.hr.front.site.co.BaseCO;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.person.DailyRespVO;
import com.auxgroup.hr.front.ws.SoapXmlBuild;

/** 
 * @author lvliuhao 
 * @version 创建时间：2018年8月16日 下午2:52:14 
 * 类说明 
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/daily")
public class DailyCalendarCO extends BaseCO {
	
	@Autowired
	private DailyCalendarService dailyCalendarService;
	
	@Value("${ws.processService.approve.address}")
	private String processURL;
	
	@Value("${ws.processService.getSched.soapAction}")
	private String getSchedSoapAction;

	
	@GetMapping(value="/getCalendar")
	public BaseResponseVO getDailyList(String emplid,String dateMonth, @SessionGain("user") UserDTO user){
		if(StringUtils.isBlank(emplid)){
			emplid = user.getEmplId();
		}
		if(StringUtils.isBlank(dateMonth)){
			dateMonth = DateUtils.format(new Date(), DateUtils.FORMAT_YYYY_MM);
		}
		//员工考勤结果记录
		List<PsCEmpMatchVw> matchs = dailyCalendarService.getEmpMatchs(emplid,dateMonth);
		if(matchs==null||matchs.isEmpty()){
			return buildRespone(Collections.EMPTY_LIST);
		}
		List<DailyRespVO> respVos = new ArrayList<DailyRespVO>();
		//休假记录
		List<PsCLaveDtlVw> dtls = dailyCalendarService.getLaveDtlsByMonth(emplid,dateMonth);
		DailyRespVO respVo;
		for (PsCEmpMatchVw match : matchs) {
			respVo = new DailyRespVO();
			respVo.setDateDay(DateUtils.format(match.getDateDay(), DateUtils.FORMAT_DEFAULT));
			List<String> unusualList =buildUnusualList(match);
			if(unusualList!=null&&!unusualList.isEmpty()){
				respVo.setUnusualList(unusualList);
				respVos.add(respVo);
			}
		}
		Map<String, DailyRespVO> respVOMap = respVos.stream().collect(Collectors.toMap(DailyRespVO::getDateDay, Function.identity()));
		String dateDay;
		List<String> unusualList;
		for (PsCLaveDtlVw dtl : dtls) {
			dateDay = DateUtils.format(dtl.getDateDay(), DateUtils.FORMAT_DEFAULT);
			//请假时长大于0的才算请假
			if(!(dtl.getCDurationDays().doubleValue()>0)){
				continue;
			}
			if(respVOMap.containsKey(dateDay)){
				if(!respVOMap.get(dateDay).getUnusualList().contains("lave")){
					respVOMap.get(dateDay).getUnusualList().add("lave");
				}
			}else{
				respVo = new DailyRespVO();
				respVo.setDateDay(dateDay);
				unusualList = new ArrayList<String>();
				unusualList.add("lave");
				respVo.setUnusualList(unusualList);
				respVOMap.put(dateDay, respVo);
			}
		}
		return buildRespone(respVOMap.values(),false);
	}
	
	/**
	 * 构建签到记录
	 * @param respVo
	 * @param crds
	 */
	private void buildSignList(DailyRespVO respVo,List<PsCEmplCrdVw> crds){
		if(crds==null||crds.isEmpty()){
			return;
		}
		List<Map<String, String>> signList = new ArrayList<Map<String,String>>();
		Map<String, String> sign;
		for (PsCEmplCrdVw crd : crds) {
			sign = new HashMap<String, String>();
			StringBuffer signStr = new StringBuffer(DateUtils.format(crd.getcCardTime(), DateUtils.FORMAT_YYYYMMDDHHMI));
			if(StringUtils.isNotBlank(crd.getDescr())){
				signStr.append("(");
				signStr.append(crd.getDescr());
				signStr.append(")");
			}
			sign.put("signTime", signStr.toString());
			signList.add(sign);
		}
		respVo.setSignList(signList);
	}
	
	
	/**
	 * 构建异常集合
	 * @param match
	 * @param dtls
	 * @return
	 */
	private List<String> buildUnusualList(PsCEmpMatchVw match){
		List<String> unusualList = new ArrayList<String>();
		//判断迟到、早退、旷工、休假图标是否显示
		if(match.getcTlLateCnt()!=null&&match.getcTlLateCnt().compareTo(new BigDecimal(0))>0){
			unusualList.add("late");
		}
		if(match.getcTlEarlyCnt()!=null&&match.getcTlEarlyCnt().compareTo(new BigDecimal(0))>0){
			unusualList.add("early");
		}
		if(match.getcTlAbsentCnt()!=null&&match.getcTlAbsentCnt().compareTo(new BigDecimal(0))>0){
			unusualList.add("absent");
		}
		return unusualList;
	}
	
	
	/**
	 * 考勤明细
	 * @param emplid
	 * @param dateDay
	 * @param user
	 * @return
	 */
	@GetMapping(value="/detail")
	public BaseResponseVO getDailyDetail(String emplid, String dateDay,@SessionGain("user") UserDTO user){
		Date day;
		try {
			day = DateUtils.parseDate(dateDay, DateUtils.FORMAT_DEFAULT);
		} catch (Exception e) {
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"请求日期格式不正确");
		}
		if(StringUtils.isBlank(emplid)){
			emplid = user.getEmplId();
		}
		PsCEmpMatchVw match = dailyCalendarService.getEmpMatch(emplid, day);
		DailyRespVO respVo = new DailyRespVO();
		//休假记录
		List<PsCLaveDtlVw> dtls = dailyCalendarService.getLaveDtlsByDay(emplid,dateDay);
		//签到记录
		List<PsCEmplCrdVw> crds = dailyCalendarService.getEmplCrds(emplid,day);
		respVo.setDateDay(dateDay);
		//构建班次名称
		respVo.setClassName(getClassName(emplid, dateDay));
		if(match==null){
			//查看是否有请假
			for (PsCLaveDtlVw dtl : dtls) {
				if(dtl.getCDurationDays().doubleValue()>0){
					List<String> unusualList = new ArrayList<String>();
					unusualList.add("lave");
					respVo.setUnusualList(unusualList);
					break;
				}
			}
		}else{
			respVo.setUnusualList(buildUnusualList(match));
			//查看是否有请假
			for (PsCLaveDtlVw dtl : dtls) {
				dateDay = DateUtils.format(dtl.getDateDay(), DateUtils.FORMAT_DEFAULT);
				if(respVo.getDateDay().equals(dateDay)){
					respVo.getUnusualList().add("lave");
					break;
				}
			}
		}
		buildSignList(respVo,crds);
		return buildRespone(respVo,false);
	}
	
	
	private String getClassName(String emplid,String dateDay){
		logger.info("daily get className param：emplid={},dateDay={}",emplid,dateDay);
		StringBuilder soapXml = new StringBuilder();
		SoapXmlBuild.buildGetClassName(soapXml,emplid,dateDay);
		String responXml = WebServiceClient.doPostSoap(processURL, soapXml.toString(), getSchedSoapAction);
		Map<String, String> result = WebServiceUtils.handleRespXml(responXml,"C_GET_SCHED_RESP");
		if(result!=null){
			return result.get("C_EMP_SCHED");
		}else{
			logger.info("daily get className result：{}",result);
			return "";
		}
	}
	
	
}
 